package com.bianmaba.css.service.security.resource;

import com.bianmaba.css.bean.entity.Resource;
import com.bianmaba.css.repository.security.resource.ResourceRepository;
import com.bianmaba.css.bean.entity.Role;
import com.bianmaba.spring.security.database.core.IResourceDetailsService;
import com.bianmaba.spring.supports.service.BaseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by cwx183898 on 2017/8/9.
 */
@Service
@Transactional
public class ResourceService extends BaseService<Resource, String> implements IResourceService, IResourceDetailsService {
    @Autowired
    private ResourceRepository repository;

    @Override
    public <S extends Resource> S save(S entity) {
        if (StringUtils.isEmpty(entity.getPk())) {
            String creator = SecurityContextHolder.getContext().getAuthentication().getName();
            entity.setCreator(creator);
        }
        return super.save(entity);
    }

    @Override
    public ResourceRepository getRepository() {
        return repository;
    }

    @Override
    public List<ConfigAttribute> findAllResources() {
        List<ConfigAttribute> attributes = new ArrayList<ConfigAttribute>(0);
        List<Resource> resources = all();
        if (!resources.isEmpty()) {
            for (Resource resource : resources) {
                attributes.add(new SecurityConfig(resource.getUrl()));
            }
        }
        return attributes;
    }


    @Override
    public List<ConfigAttribute> findRolesOfResource(String url) {
        List<ConfigAttribute> attributes = new ArrayList<ConfigAttribute>(0);
        Resource resource = repository.findByUrl(url);
        if (!resource.getRoles().isEmpty()) {
            for (Role role : resource.getRoles()) {
                attributes.add(new SecurityConfig(role.getName()));
            }
        }
        return attributes;
    }
}
